package com.crazymaker.springcloud.demo.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.LinkedHashMap;
import java.util.Map;

public class DemoAuthProvider implements AuthenticationProvider {

    private Map<String, String> map = new LinkedHashMap<>();

    public DemoAuthProvider() {
        map.put("zhangsan", "123456");
        map.put("lisi", "12345678");
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 执行验证逻辑，模拟数据库查询
        DemoToken demoToken = (DemoToken) authentication;
        String formUserName = demoToken.getPrincipal().toString();
        if (map.containsKey(formUserName)) {
            String formPwd = demoToken.getCredentials().toString();
            if (!formPwd.equalsIgnoreCase(map.get(formUserName))) {
                demoToken.setAuthenticated(false);
                throw new BadCredentialsException(formUserName + "密码输入有误");
            } else {
                demoToken.setAuthenticated(true);
            }
        } else {
            demoToken.setAuthenticated(false);
            throw new BadCredentialsException(formUserName + "当前用户不存在");
        }
        return demoToken;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.isAssignableFrom(DemoToken.class);
    }
}
